package com.example.yilanchatserver.business.freechat;

import com.alibaba.fastjson.JSON;
import com.example.yilanchatserver.application.controller.vo.ErnieBotStreamRespVO;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.Disposable;
import reactor.core.publisher.FluxSink;

@Slf4j
public class ErnieBotSubscriber implements Subscriber<String>, Disposable {
    private final FluxSink<String> emitter;
    private Subscription subscription;

    private final StringBuilder resultContent;

    public ErnieBotSubscriber(FluxSink<String> emitter) {
        this.emitter = emitter;
        this.resultContent = new StringBuilder();
    }

    @Override
    public void onSubscribe(Subscription subscription) {
        this.subscription = subscription;
        subscription.request(1);
    }

    @Override
    public void onNext(String data) {
//        log.info("ErnieBot 返回数据：{}", data);
        try {
            // 处理返回数据
            if (StringUtils.isNotEmpty(data)) {
                ErnieBotStreamRespVO respVO = JSON.parseObject(data, ErnieBotStreamRespVO.class);
                // 是否已结束
                Boolean isEnd = respVO.getIsEnd();
                if (isEnd) {
                    log.info("ErnieBot 返回数据结束了");
                    subscription.request(1);
                    emitter.complete();
                } else {
                    String content = respVO.getResult();
                    emitter.next(content);
                    resultContent.append(content);
                    subscription.request(1);
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
            emitter.next("[Error]");
            emitter.complete();
        }
    }

    @Override
    public void onError(Throwable t) {
        log.error("ErnieBot 返回数据异常：{}", t.getMessage());
        emitter.error(t);
    }

    @Override
    public void onComplete() {
        log.info("ErnieBot 返回数据完成");
        emitter.next("[Done]");
        emitter.complete();
    }

    @Override
    public void dispose() {
        log.warn("ErnieBot 返回数据关闭");
        emitter.complete();
    }

}
